//
//  SpeechManager.m
//  suRead
//
//  Created by lidi on 2018/5/30.
//  Copyright © 2018年 bao. All rights reserved.
//

#import "SpeechManager.h"
#import <AVFoundation/AVFoundation.h>

//#error 请在官网新建app，配置bundleId，并在此填写相关参数
NSString * const APP_ID = @"11304278";
NSString * const API_KEY = @"5qGfEQWKKSMGdheResUd0OCs";
NSString * const SECRET_KEY = @"ysHIqb0PCBP8bzG07a5bHLEEEfNRgDyS";

@interface SpeechManager()<BDSSpeechSynthesizerDelegate>

@property(nonatomic,strong) NSMutableArray *textQueue;
@property(nonatomic,copy)void(^complete)();
@end

@implementation SpeechManager

static SpeechManager *instance = nil;

/** 单例类方法 */
+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self new];
        instance.textQueue = [NSMutableArray array];
        [instance initConfig];
        [[BDSSpeechSynthesizer sharedInstance] setAudioSessionCategory:AVAudioSessionCategoryPlayback];
    });
    
    return instance;
}

- (void)initConfig {
    [self configureSDK];
    [self configureOnlineTTS];
    [self configureOfflineTTS];
}

- (BDSSynthesizerStatus)status {
    return [[BDSSpeechSynthesizer sharedInstance] synthesizerStatus];
}

- (void)speak:(NSString *)text complete:(void (^)())complete {
    
    //初始化播放状态
    [self cancel];
    self.complete = complete;
    
    //切分播放内容
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    NSString *text_ = [attrStr string];
    NSInteger itemLength = 100;
    NSString *temp = text_;
    while ([temp length] > 0) {
        if ([temp length] > itemLength) {
            [self.textQueue addObject:[temp substringToIndex:itemLength]];
            temp = [temp substringFromIndex:itemLength];
        } else {
            [self.textQueue addObject:temp];
            temp = @"";
        }
    }
    
    //开始播放
    [self startSpeech];
}

- (void)startSpeech {
    if ([self.textQueue count] > 0) {
        //开始播报
        NSError *error;
        NSUInteger sentenceId = [[BDSSpeechSynthesizer sharedInstance] speakSentence:[self.textQueue firstObject] withError:&error];
        if (!error) {
            NSLog(@"%ld",sentenceId);
        } else {
            NSLog(@"%@",error.description);
        }
    } else {
        //播报完成
        if (self.complete) {
            self.complete();
        }
    }

}

- (void)cancel {
    [[BDSSpeechSynthesizer sharedInstance] cancel];
    [self.textQueue removeAllObjects];
}

- (void)pause {
    [[BDSSpeechSynthesizer sharedInstance] pause];
}

- (void)resume {
    [[BDSSpeechSynthesizer sharedInstance] resume];
}

- (void)configureSDK {
    NSLog(@"TTS version info: %@", [BDSSpeechSynthesizer version]);
    //[BDSSpeechSynthesizer setLogLevel:BDS_PUBLIC_LOG_VERBOSE];
    [[BDSSpeechSynthesizer sharedInstance] setSynthesizerDelegate:self];
    [self configureOnlineTTS];
    [self configureOfflineTTS];
}

- (void)configureOnlineTTS {
    [[BDSSpeechSynthesizer sharedInstance] setApiKey:API_KEY withSecretKey:SECRET_KEY];
    
    [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback error:nil];
    //    [[BDSSpeechSynthesizer sharedInstance] setSynthParam:@(BDS_SYNTHESIZER_SPEAKER_DYY) forKey:BDS_SYNTHESIZER_PARAM_SPEAKER];
    //    [[BDSSpeechSynthesizer sharedInstance] setSynthParam:@(10) forKey:BDS_SYNTHESIZER_PARAM_ONLINE_REQUEST_TIMEOUT];
}

- (void)configureOfflineTTS {
    NSError *err = nil;
    // 在这里选择不同的离线音库（请在XCode中Add相应的资源文件），同一时间只能load一个离线音库。根据网络状况和配置，SDK可能会自动切换到离线合成。
    NSString* offlineEngineSpeechData = [[NSBundle mainBundle] pathForResource:@"Chinese_And_English_Speech_Female" ofType:@"dat"];
    
    NSString* offlineChineseAndEnglishTextData = [[NSBundle mainBundle] pathForResource:@"Chinese_And_English_Text" ofType:@"dat"];
    
    err = [[BDSSpeechSynthesizer sharedInstance] loadOfflineEngine:offlineChineseAndEnglishTextData speechDataPath:offlineEngineSpeechData licenseFilePath:nil withAppCode:APP_ID];
    if(err){
        //[self displayError:err withTitle:@"Offline TTS init failed"];
        return;
    }
    
}

//MARK: - BDSSpeechSynthesizerDelegate
- (void)synthesizerStartWorkingSentence:(NSInteger)SynthesizeSentence {
    //开始合成
}

- (void)synthesizerFinishWorkingSentence:(NSInteger)SynthesizeSentence {
    //合成完成
}

- (void)synthesizerSpeechStartSentence:(NSInteger)SpeakSentence {
    //开始播放
}

- (void)synthesizerSpeechEndSentence:(NSInteger)SpeakSentence {
    //播放完成
    //移除第一条
    if ([self.textQueue count] > 0) {
        [self.textQueue removeObjectAtIndex:0];
        [self startSpeech];
    }
}

@end
